//
//  VideoViewController.m
//  Tang
//
//  Created by 邓芮 on 15/12/3.
//  Copyright © 2015年 352324497@qq.com. All rights reserved.
//

#import "VideoViewController.h"
#import "VideoCell.h"
#import "VideoViewModel.h"
#import "VideoViewDetailModel.h"
#import "VideoHeaderCell.h"
#import "VideoDetailController.h"

#define Kurl  @"http://app.meilihuli.com/api/course/category"
@interface VideoViewController ()<UITableViewDataSource, UITableViewDelegate,VideoCellDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *modelArray;
@end
static NSString *cellForSec = @"cell";
static NSString *headerIndentifier = @"header";
@implementation VideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KHeight-104) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = NO;
    
    [self.tableView registerClass:[VideoCell class] forCellReuseIdentifier:cellForSec];
    [self.tableView registerClass:[VideoHeaderCell class] forHeaderFooterViewReuseIdentifier:headerIndentifier];
    
    [self.view addSubview:self.tableView];
    //self.tableView.bounces = NO;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self requestWithUrl:Kurl];
        [self.tableView.mj_header endRefreshing];
    }];
    
    
    if (![[NetworkState shareInstance]reachablity])
    {
        if ([self isHaveFilePath])
        {
            NSString *newPath = [self isHaveFilePath];
            NSData *data = [NSData dataWithContentsOfFile:newPath];
            self.modelArray = [NSMutableArray array];
            NSDictionary *firDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            for (NSDictionary *secDic in firDic[@"data"])
            {
                VideoViewModel *oneModel = [[VideoViewModel alloc] init];
                [oneModel setValuesForKeysWithDictionary:secDic];
                oneModel.sub_catArray = [NSMutableArray array];
                for (NSDictionary *thrDic in secDic[@"sub_category"])
                {
                    VideoViewDetailModel *secModel = [[VideoViewDetailModel alloc] init];
                    [secModel setValuesForKeysWithDictionary:thrDic];
                    [oneModel.sub_catArray addObject:secModel];
                }
                [self.modelArray addObject:oneModel];
            
        }
    }
    }
    else
    {
        [self requestWithUrl:Kurl];
    }
    

    
}


#pragma  mark ---数据解析
- (void)requestWithUrl:(NSString *)url
{
    [[NetworkState shareInstance]reachablityStatesWithDongHua:self];
    [[[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
    {
        if (data == nil)
        {
            NSLog(@"请求出错,");
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲, 网络好像不是很给力哦~~~" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *OKaction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            [alertView addAction:OKaction];
            [self presentViewController:alertView animated:YES completion:nil];
            return ;
        }
        if (![self isHaveFilePath])
        {
            [data writeToFile :[self creatNewFilePath] atomically:YES];
        }
        
        
        
        self.modelArray = [NSMutableArray array];
        NSDictionary *firDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        for (NSDictionary *secDic in firDic[@"data"])
        {
            VideoViewModel *oneModel = [[VideoViewModel alloc] init];
            [oneModel setValuesForKeysWithDictionary:secDic];
            oneModel.sub_catArray = [NSMutableArray array];
            for (NSDictionary *thrDic in secDic[@"sub_category"])
            {
                VideoViewDetailModel *secModel = [[VideoViewDetailModel alloc] init];
                [secModel setValuesForKeysWithDictionary:thrDic];
                [oneModel.sub_catArray addObject:secModel];
            }
            [self.modelArray addObject:oneModel];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^
        {
            [[NetworkState shareInstance]finshYYToVc:self];
            [self.tableView reloadData];
            
        });
        
    }] resume];
    
}


#pragma mark --- 做数据保存--
- (NSString *)newFilePath
{
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:@"videoView.plist"];
}

- (NSString *)creatNewFilePath
{
    NSString *newPath = [self newFilePath];
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:newPath])
    {
        [manager createFileAtPath:newPath contents:nil attributes:nil];
    }
    return newPath;
    
}
- (NSString *)isHaveFilePath
{
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *newPath = [self newFilePath];
    if ([manager fileExistsAtPath:newPath])
    {
        return newPath;
    }
    else
    {
        return nil;
    }

}
#pragma mark --返回分区个数--
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.modelArray.count;
}


#pragma mark --返回分区行数--
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
#pragma mark --返回cell--

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoCell *cell = [tableView dequeueReusableCellWithIdentifier:cellForSec forIndexPath:indexPath];
    cell.delegate = self;
    VideoViewModel *model = self.modelArray[indexPath.section];
    cell.model = model;
    
    
    [cell.collectionView reloadData];
    return cell;
}



#pragma mark --返回cell高--
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [VideoCell heightForCellWithModel:self.modelArray[indexPath.section]];
}
#pragma mark --返回表头高--
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    VideoViewModel * model = self.modelArray[section];
    VideoHeaderCell *aHeader = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerIndentifier];
    aHeader.tag = 1000 + section;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [aHeader addGestureRecognizer:tap];
    aHeader.model = model;
    
    
    
   
    
    return aHeader;
    
}



- (void)tapAction:(UITapGestureRecognizer *)tap
{
    VideoHeaderCell *aView = (VideoHeaderCell *)tap.view;
    NSInteger num = aView.tag - 1000;
    VideoViewModel *mode = self.modelArray[num];
    VideoDetailController *videoVc = [[VideoDetailController alloc] init];
    
    videoVc.titleName = mode.name;
    videoVc.coure_id = mode.category_id;
    
    [self.navigationController pushViewController:videoVc animated:YES ];
    
    
    
}

#pragma mark --返回表头高--
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return KWidth * 35 / 414;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

#pragma mark  --代理跳转----
- (void)jumpVcWithModel:(VideoViewDetailModel *)model
{
    VideoDetailController *videoVc = [[VideoDetailController alloc] init];
    
    videoVc.titleName = model.name;
    videoVc.coure_id = model.category_id;
    
    [self.navigationController pushViewController:videoVc animated:YES ];

    
}




@end
